package com.xw.tools.view;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.io.ByteArrayInputStream;

public class QRCodeWin extends AbstractWin {

    private TextArea inputTextArea;

    private ImageView imageView;

    private Button button;

    private void start() {
        Stage stage = new Stage();
        stage.setTitle("二维码");
        //stage.initModality(Modality.WINDOW_MODAL);
        //stage.initOwner(primaryStage);
        Scene scene = new Scene(new VBox(), 800, 495);
        initView(scene, stage);
        stage.setScene(scene);
        stage.show();
    }

    private void initView(Scene scene, Stage stage) {
        inputTextArea = new TextArea();
        inputTextArea.setFont(Font.font(16));
        imageView = new ImageView();
        imageView.setFitHeight(300);
        imageView.setFitWidth(300);
        button = new Button("生成");
        button.setOnAction(event -> {
            String text = inputTextArea.getText();
            if (StrUtil.isBlank(text)) {
                return;
            }
            byte[] bytes = QrCodeUtil.generatePng(text, 300, 300);
            imageView.setImage(new Image(new ByteArrayInputStream(bytes)));
        });

        VBox box = (VBox) scene.getRoot();
        box.getChildren().add(imageView);
        box.getChildren().add(button);
        box.getChildren().add(inputTextArea);
        VBox.setVgrow(inputTextArea,  Priority.ALWAYS);
    }

    @Override
    public void show() {
        start();
    }
}
